package com.chivan.encoder.recorder;

import android.content.Context;
import android.media.AudioRecord;

import com.chivan.encoder.log.Logcat;

/*
 * Create by weslywang on 2019-11-06
 * Copyright © Tencent
 *
 * Description:
 */

public class QTAudioRecorder extends BaseAudioRecorder {

    private AudioRecord audioRecord;

    public QTAudioRecorder(Context context) {
        super(context);
    }

    @Override
    protected int startNativeRecorder() {
        if (audioRecord != null) {
            Logcat.e("录音失败：已经开始录音");
            stopNativeRecorder();
        }
        if (!init()) {
            Logcat.e("录音失败：录音机初始化失败");
            return -1;
        }

        try {
            Logcat.i("启动手机录音机");
            audioRecord.startRecording();
            return 0;
        } catch (Exception e) {
            Logcat.e("启动录音机失败!!!!!!!!!!!!!" + e.toString());
            return -1;
        }
    }

    @Override
    protected int readNativeRecorderData(byte[] audiodataTmp) {
        try {
            int readsize = audioRecord.read(audiodataTmp, 0, bufferSize);
            String flag = "";
            if (readsize != audiodataTmp.length) {
                flag = " !!!!";
            }
            Logcat.i("录音机读取数据: readSize=" + readsize + ", audiodataTmp最终长度：" + audiodataTmp.length + flag);
//            Logcat.d(FileUtil.bytesToHexString(audiodataTmp));
            return readsize;
        } catch (Exception e) {
            Logcat.e("录音机读取数据出错" + e.toString());
        }
        return 0;
    }

    @Override
    protected String stopNativeRecorder() {
        if (audioRecord != null) {
            try {
                audioRecord.stop();//部分机型，例如：小米、联想会出现异常，异常原因是录音的硬件资源被申请了，但是没有释放，必须在停止录音之后把audioRecord对象置空
            } catch (Exception e) {
                Logcat.e("录音recorder停止出错:" + e.getMessage());
            }
        }
        if (audioRecord != null) {
            try {
                audioRecord.release();
            } catch (Exception e) {
                Logcat.e("录音recorder释放资源出错:" + e.getMessage());
            }
        }
        audioRecord = null;
        return "";
    }

    /**
     * 初始化播放器
     */
    private boolean init() {
        long arsBegin = System.currentTimeMillis();

        bufferSize = AudioRecord.getMinBufferSize(sampleRate, channel, audioFormat);
        if (AudioRecord.ERROR == bufferSize ||
                AudioRecord.ERROR_BAD_VALUE == bufferSize) {
            //灯塔数据上报:AudioRecord初始化不成功
            Logcat.e("录音机初始化失败：GETMINBUFFERSIZE_ERROR");
//            DataReport.getInstance().report(DataReport.EVENT_AUDIO_RECORD_GETMINBUFFERSIZE_ERROR);
            return false;
        }
        //每次读取的数据，是COMPRESSION_MIN_BYTE_LEN的整数倍
        int num = bufferSize / MIN_BYTE_LEN_200_ms + 1;
        bufferSize = num * MIN_BYTE_LEN_200_ms;
        if (null != audioRecord) {
            audioRecord = null;
            Logcat.e("录音机初始化失败：重复初始化");
            //灯塔数据上报:AudioRecord在初始化的时候，发现其不为空
        }
        // 创建AudioRecord对象,是有可能失败的
        //在小米的一些机型上，当第一次录音的时候，会重新确认录音权限。如果这个时候用户拒绝，则audioRecord是无法初始化成功的
        //所以必须在此处再重新判断一次audioRecord是否为空
        try {
            audioRecord = new AudioRecord(audioSource, sampleRate, channel, audioFormat, bufferSize);
            long arsDuration = System.currentTimeMillis() - arsBegin;
            Logcat.i("录音机初始化耗时" + arsDuration + ", bufferSize=" + bufferSize);
        } catch (Exception e) {
            Logcat.e("录音机初始化失败：" + e.getMessage());
            audioRecord = null;
            return false;
        }
        if (null == audioRecord)
            return false;
        return true;
    }

}
